from django.core.cache import cache
from django.http import JsonResponse
from django.views import View

from apps.areas.models import Area


# Create your views here.


class AreasView(View):

    def get(self, request):
        province_list = cache.get('province_list')
        if not province_list:
            provinces = Area.objects.filter(parent_id=None)

            province_list = [{'id': province.id, 'name': province.name} for province in provinces]

            cache.set('province_list', province_list, 3600 * 24)

        return JsonResponse({'code': 0, 'errmsg': 'OK', 'province_list': province_list})


class SubAreasView(View):

    def get(self, request, parent_id):
        parent = Area.objects.get(pk=parent_id)

        sub_list = cache.get(f'{parent_id}:sub_list')
        if not sub_list:
            subs = parent.subs.all()

            sub_list = [{'id': sub.id, 'name': sub.name} for sub in subs]

            cache.set(f'{parent_id}:sub_list', sub_list, 3600 * 24)

        sub_data = {
            'id': parent_id,
            'name': parent.name,
            'subs': sub_list
        }

        return JsonResponse({'code': 0, 'errmsg': 'OK', 'sub_data': sub_data})
